package cn.jdemo.base.clazz;

import java.lang.reflect.Method;
import java.util.ArrayList;

/**
 * 泛型擦除
 * <a href="https://blog.csdn.net/qq_43546676/article/details/128790980"></>
 */
public class TypeClear3 {

    /**
     * 输出内容:
     * [张三, 李四, 21]
     * Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
     * 	at cn.jdemo.base.clazz.TypeClear3.main(TypeClear3.java:24)
     */
    public static void main(String[] args) throws Exception {
        ArrayList<String> list = new ArrayList<>();
        list.add("张三");
        list.add("李四");
        // 通过反射绕过编译
        Class clazz = list.getClass();

        // 这里必须是Object，因为泛型擦除规则：ArrayList<E>中E没有泛型上界，所以泛型擦除后占位符E用Object代替
        Method method = clazz.getMethod("add", Object.class);
        method.invoke(list, 21);

        System.out.println(list);
        System.out.println(list.get(2));
    }
}
